package go2

import (
	"encoding/json"
	"errors"
	"go2/log"
)

func JsonMarshalE(v any) []byte {
	if v == nil {
		log.Error("v is nil")
		return nil
	}

	data, err := json.Marshal(v)
	if err != nil {
		log.Errorf("%v ===> %v", v, err)
		return nil
	}

	return data
}

func JsonUnmarshalE(data []byte, v any) error {
	if data == nil {
		log.Error("data is nil")
		return errors.New("data is nil")
	}

	if len(data) == 0 {
		log.Error("data len is 0")
		return errors.New("data len is 0")
	}

	if err := json.Unmarshal(data, v); err != nil {
		log.Errorf("%s... ===> %v", string(data[:100]), err)
		return err
	}

	if v == nil {
		log.Error("v is nil")
		return errors.New("v is nil")
	}

	return nil
}

func JsonUnmarshalB(data []byte, v any) bool {
	if err := JsonUnmarshalE(data, v); err == nil {
		return true
	}
	return false
}
